package uk.ac.lkl.lpp.model.xml;



import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import uk.ac.lkl.common.util.ds.AbstractNotifyingList;
import uk.ac.lkl.common.util.ds.NotifyingList;
import uk.ac.lkl.lpp.model.PedagogyPlanModel;

import uk.ac.lkl.lpp.model.ldo.ModuleAim;
import uk.ac.lkl.lpp.model.ldo.TeachingMethod;
import uk.ac.lkl.lpp.ui.BackCompat;


public class TeachingMethodSetProcessor extends ModelElementProcessor {

    public TeachingMethodSetProcessor() {
        super("TeachingMethodSet");
    }


    /**
     * write TMs to TeachingMethodSet element
     */
    public void convertDataToElements(PedagogyPlanModel plan,
                                      Document document,
                                      Element pedagogyPlanElement) {
        // should be done in base class
        Element teachingMethodSetElement = document
                .createElement("TeachingMethodSet");
        pedagogyPlanElement.appendChild(teachingMethodSetElement);

        AbstractNotifyingList<TeachingMethod> list = (AbstractNotifyingList<TeachingMethod>) plan
                .getList("main", TeachingMethod.class);
        for (int i = 0; i < list.size(); i++) {
            TeachingMethod teachingMethod = list.get(i);
            Element teachingMethodElement = document
                    .createElement("TeachingMethod");

            teachingMethodElement.setAttribute("index", Integer.toString(i));
            teachingMethodElement.setAttribute("title", teachingMethod
                    .getTitle());
            teachingMethodElement
                    .setAttribute("link", teachingMethod.getLink());
            teachingMethodElement.setTextContent(teachingMethod
                    .getDescription());

            teachingMethodSetElement.appendChild(teachingMethodElement);
        }
    }


    @Override
    public void convertElementToData(PedagogyPlanModel plan,
                                     Element parentElement) {
        AbstractNotifyingList<TeachingMethod> list = new NotifyingList<TeachingMethod>(
                TeachingMethod.class);
        NodeList nodes = parentElement.getElementsByTagName("TeachingMethod");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element childElement = (Element) nodes.item(i);
            String title = childElement.getAttribute("title");
            String description = childElement.getTextContent();
            String link = childElement.getAttribute("link");
            TeachingMethod teachingMethod = new TeachingMethod(title,
                    description, link);
            BackCompat.backPatch(plan.getVersion(), teachingMethod);

            list.add(teachingMethod);
        }
        plan.addList("main", TeachingMethod.class, list);
    }

}
